module.exports = app => {
    const express = require("express")
    const router = express.Router({
        mergeParams: true   //导入父级参数到子级配置
    });
    const Users = require('../../models/User');
    const assert = require('http-assert'); //快速验证,抛出异常
    //新增
    router.post("/", async (req, res) => {
        if (req.params.resource == "invitation" || req.params.resource == "Announce") {
            req.body.user = req.user.id
        }
        const data = await req.Model.create(req.body)
        res.send(data)
    })
    //查找单个id
    router.get("/:id", async (req, res) => {
        const data = await req.Model.findById(req.params.id).populate('User')
        assert(data, 401, "没有找到")
        res.send(data)
    })
 
    //修改
    router.put("/:id", async (req, res) => {
        const doc = await req.Model.findByIdAndUpdate(req.params.id, req.body)
        res.send(doc)
    })
    //删除
    router.delete("/:id", async (req, res) => {
        const doc = await req.Model.findByIdAndDelete(req.params.id, req.body);
        // const  req.Model = await req.Model.findById(req.params.id);
        // await req.Model.remove();
        assert(doc, 401, "删除失败")
        // if (!doc) {
        //     res.status(401).send({
        //         message: "删除失败"
        //     })
        // }
        res.send({
            message: "删除成功"
        })
    })

    //get列表
    router.get('/', async (req, res) => {
        const list = await req.Model.find().populate('Category')
        assert(list, 404, "请求失败")
        res.send(list)
    })


    // 获取分页搜索列表
    const listRouter = express.Router();

    //post获取列表
    listRouter.post('/', async (req, res) => {
        // console.log(req.body)
        const { size = 10, current = 1, name } = req.body;
        let total;
        let list = [];
        if (name) {
            console.log(name, '')
            total = await req.Model.where({ name }).countDocuments()
            list = await req.Model.find().populate(["Category", "User"]).where({ name });
        } else {
            total = await req.Model.countDocuments()
            list = await req.Model.find().populate(["Category", "User"]).skip(size * (current - 1)).limit(size);
        }
        const page = {
            total,
            size,
            current,
            list
        };
        res.send(page)
    })

    // 中间件- 找出对于的数据库的表
    const reqModel = (req, res, next) => {
        const ModelName = require("inflection").classify(req.params.resource);   //需要npm i inflection 引入
        req.Model = require(`../../models/${ModelName}`)
        next();
    }

    const jwt = require("jsonwebtoken");
    // //中间件- 验证token返回id
    const auth = require(`../../middle/auth`)(app,["admin"])

    app.use('/admin/api/rest/:resource', auth, reqModel, router);   //  增删查改
    app.use("/admin/api/list/:resource", auth, reqModel, listRouter)  //搜索
}